<?php
/**
 * Miffos framework
 * ----------------------------------------------
 *
 * Copyright (c) 2008, 2009 Martin Sadový (http://sodae.cz)
 *
 * This source file is subject to the "Miffos license" that is bundled
 * with this package in the file license.txt.
 *
 * @copyright  Copyright (c) 2008, 2009 Martin Sadový
 * @license    license.txt
 * @link       http://miffos.sodae.cz
 * @package    miffos
 * @version    $Id$
 */


  class FormFileInput extends FormInputExtends
  {
    protected $type = 'file';

    private $allowType = array();

    private $allowSize;

    public function setAllowType()
    {
        $arg = func_get_args();
        if(count($arg) == 1 AND is_array( $arg[0] )){
            $this->allowType[] = $arg[0];
        }else{
            $this->allowType = $arg;
        }
        return $this;
    }

    public function setMaxSize($size)
    {
        $this->allowSize = $size;
        return $this;
    }

    public function getAllowType()
    {
        return $this->allowType;
    }

    public function getAllowSize()
    {
        return $this->allowSize;
    }
  }

  class FormUploadHelper
  {
      public $name;

      public $tmp;

      public $size;

      public $type;

      public $ok;

      private $control;

      public $error;
      
      public function __construct($control,$data)
      {
          $this->name     = $data['name'][$control->getName()];
          $this->tmp      = $data['tmp_name'][$control->getName()];
          $this->size     = $data['size'][$control->getName()];
          $this->type     = $data['type'][$control->getName()];
          $this->ok       = ($data['error'][$control->getName()] == UPLOAD_ERR_OK);
          $this->control  = $control;
      }

      public function isAllow()
      {
          if($this->control->getAllowSize() > 0 AND $this->control->getAllowSize() < $this->size){
              $this->error = 'size';
              return false;
          }
          if(count($this->control->getAllowType()) > 0 AND !in_array($this->type,$this->control->getAllowType())){
              $this->error = 'type';
              return false;
          }
          return true;
      }

      public function moveto($path,$setName=true){

          if(!$this->ok OR !$this->isAllow())
             return false;

          if($setName)
             $path = $path.$this->name;

          if(empty($path))
             $path = $this->name;

          if(!move_uploaded_file($this->tmp, $path))
             return false;

          return true;

      }
  }
?>